package jsp.servlet;

import jsp.model.User;
import jsp.servcie.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/userLogin")
public class UserLoginServlet extends HttpServlet {

    private UserService service = new UserService();


    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        User user = service.getByUsername(username);

        if (user == null) {
            request.setAttribute("message", "用户名不存在");
            request.setAttribute("username", username);
            request.setAttribute("password", password);
            request.getRequestDispatcher(request.getContextPath() + "/userLogin.jsp").forward(request, response);
            return;
        }

        if (!password.equals(user.getPassword())) {
            request.setAttribute("message", "密码错误");
            request.setAttribute("username", username);
            request.setAttribute("password", password);
            request.getRequestDispatcher(request.getContextPath() + "/userLogin.jsp").forward(request, response);
            return;
        }

        request.getSession().setAttribute("user", user);
        response.sendRedirect(request.getContextPath() + "/userList");
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.sendRedirect(request.getContextPath() + "/userLogin.jsp");
    }

}
